<?php
class WapiExt extends wapi {

//Assuming this is running on a Linux machine, I've always handled it like this:
//
//exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
//
//This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.
//
//That lets you easily monitor what the process is doing and if it's still running.
//
//function isRunning($pid){
//    try{
//        $result = shell_exec(sprintf("ps %d", $pid));
//        if( count(preg_split("/\n/", $result)) > 2){
//            return true;
//        }
//    }catch(Exception $e){}
//
//    return false;
//}



	function rand_string($strsize) {
		srand(time());
		$ret = '';
		for($i=1;$i<=$strsize;$i++) {
			#$char = chr(rand(65, 90));
			$char = chr(rand(97, 122));
			$ret .= $char;
		}
		return $ret;
	}
	function add_hidden_input($inputval) {
	    global $inputindex, $inputpre;
	    if ($inputpre == '') {
		$inputpre = $this->rand_string(8);
		$inputindex = 0;
	    }
	    $inputindex ++;
	    $inputid = $inputpre . $inputindex;
	    echo "<input type=\"hidden\" name=\"".$inputid."n\" id=\"".$inputid."\" value=\"".$inputval."\" />";
	    return $inputid;
	}
	function build_quick_link($scheme, $path) {
	    echo "<li><span class=\"quicklink\">";
	    $path = rtrim($path,'/');
	    $path = $this->clean($path,'/',true);
	    $qlink = "$scheme://";
	    $part = "$scheme://";
	    $qlinkcnt = 0;
	    $qlinkid = $this->add_hidden_input($qlink);
	    $applink = $this->run("browse_" . $scheme . "($qlinkid:value)->$this->target_id",$this->thisfile);
	    echo "<a href=\"javascript:void(0)\" onclick=\"$applink\">$part</a>";
	    if ($path != '') {
		$parts = explode('/', $path);
		foreach ($parts as $part) {
		    $qlinkcnt ++;
		    if ($qlinkcnt > 1) {
			$qlink .= '/';
			echo "/";
		    }
		    $qlink .= $part;
		    $qlinkid = $this->add_hidden_input($qlink);
		    $applink = $this->run("browse_" . $scheme . "($qlinkid:value)->$this->target_id",$this->thisfile);
		    echo "<a href=\"javascript:void(0)\" onclick=\"$applink\">$part</a>";
		}
	    }
	    echo "</span></li>";
	}
	function conv_bytes($bytecnt) {
	    $t = $bytecnt;
	    if (number_format($t / 1024, 2) >= 1) {
		$t = $t / 1024;
		if (number_format($t / 1024, 2) >= 1) {
		    $t = $t / 1024;
		    if (number_format($t / 1024, 2) >= 1) {
			$t = $t / 1024;
			$ret = number_format($t, 2) . ' GB';
		    } else {
			$ret = number_format($t, 2) . ' MB';
		    }
		} else {
		    $ret = number_format($t, 2) . ' KB';
		}
	    } else {
		$ret = $bytecnt . ' bytes';
	    }
	    return $ret;
	}

	function display_results($results, $displaytype='ulist', $sortbytitle=true, $noimg=false){
	    if ($sortbytitle) {
			$results = $this->msort($results,'title');
	    }
	    if ($displaytype == '') {
			$displaytype = 'ulist';
	    }
	    foreach ($results as $res) {
			$title = $res['title'];
			$link = $res['link'];
			$img = $res['img'];
			$det = $res['details'];
			$href = $res['href'];
			if ($href == '') {
			    $href = 'javascript:void(0);';
			}
			$li = '';
			switch ($displaytype) {
			    case 'icon_med' :
					echo "<div class=\"menu_item\"><a href=\"$link\"><div class=\"menu_item_img rounded\" style=\"width:48px; height:48px; background-image:url('$img');\"></div><div class=\"menu_item_title\">$title</div></a></div>\n";
					break;
			    case 'ulist' :
					$li = "<li>";
					if ($img != '' && !$noimg) {
					    $li .= "<img class=\"resultImg\" src=\"$img\" />";
					}
					$li .= "<a class=\"result\" href=\"$href\" onclick=\"$link\">$title</a>";
					if ($det != '') {
					    $li .= "<p class=\"resultDetails\">$det</p>";
					}
					$li .= "</li>\n";
					echo $li;
					break;
			    default :
					break;
			}
	    }
	    $this->js("window.scrollTo(0,1);");
	    #$this->js("hideURLbar();");
	}
	// App Javascript code handlers
	function app_load_js_file($js_file,$id = '',$force_refresh=false){
		if ($id == '') {
			$id = md5($js_file);
		}
		if ($force_refresh){
			$js_file .= "?force_refresh=" . time();
		}
		$_SESSION['APPS'][$this->app_class]['JS'][$id] = $js_file;
		$div_id = $this->app_class . '_js_' . $id;
		$js_code="var headID = document.getElementsByTagName('head')[0];
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.id = '$div_id';";
		$js_file = $this->app_rel_path . '/' . $js_file;
		$js_code.="newScript.src = '$js_file';headID.appendChild(newScript)";
		$this->js($js_code);
		return $id;
	}
	function app_unload_js_file($id){
		$div_id = $this->app_class . '_js_' . $id;
		if (isset($_SESSION['APPS'][$this->app_class]['JS'][$id])) {
			$this->js("removeById('$div_id')");
			unset($_SESSION['APPS'][$this->app_class]['JS'][$id]);
		}
	}
	function app_unload_js_all(){
		if (isset($_SESSION['APPS'][$this->app_class]['JS'])) {
		    foreach ($_SESSION['APPS'][$this->app_class]['JS'] as $key => $val) {
				$this->app_unload_js_file($key);
	    	}
		}
	}
	// End App Javascript code handlers

	// IUI interface functions
	function iui_deselect($objid) {
		$this->js("document.getElementById('$objid').removeAttribute('selected');");
	}
	function iui_ShowPage($page) {
		$reg='/^#.*/';
		if ($this->qregex($page,$reg) !== true) {
			# Show page
			$this->js("window.iui.showPageByHref('$page')");
		} else {
			# Show page by id
			$page = substr($page,1);
			$this->js("window.iui.showPageById('$page')");
		}
		#return false;
	}
	function append_css_file ($file) {
		$js_code="var headID = document.getElementsByTagName('head')[0];
			var cssNode = document.createElement('link');
			cssNode.type = 'text/css';
			cssNode.rel = 'stylesheet';
			cssNode.href = '$file';
			cssNode.media = 'screen';
			headID.appendChild(cssNode);";
		$this->js($js_code);
	}
	function load_js_file ($id='',$js_file) {
		$js_code="var headID = document.getElementsByTagName('head')[0];
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.id = '$id';";

		$js_code.="newScript.src = '$js_file';
			headID.appendChild(newScript)";
		$this->js($js_code);
	}
	function load_js_file_inline ($id,$js_file,$onload='') {
		$file_code = $this->read_file($js_file);
		$js_code="var headID = document.getElementsByTagName('head')[0];
			var newScript = document.createElement('script');
			newScript.type = 'text/javascript';
			newScript.id = '$id';";

		$js_code.="headID.appendChild(newScript)";
		$this->js($js_code);
		$this->text($file_code,$id);

		if ($onload != ''){
			$this->js($onload);
		}
	}
	function delayed_call_back ($func_code,$del_time) {
		$func_js = $this->run($func_code);
		$delay_js = "setTimeout(\"$func_js\", $del_time );";
		$this->js($delay_js);
	}
	function delayed_js ($delay_js,$del_time) {
		$delay_js = "setTimeout(\"$func_js\", $del_time );";
		$this->js($delay_js);
	}
	function qregex($data, $regval){
		if (preg_match($regval, $data, $matches)) {
			if ($matches[0] == $data) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}


	// Saja Localizers
	function run($commands, $process_file=null, $use_history='false')
	{
		$backtrace = debug_backtrace();
		if (isset($backtrace[1])) {
			$cfile = $backtrace[1]['file'];
			$cclass = $backtrace[1]['class'];
			$cfunc = $backtrace[1]['function'];
		} else {
			$stop = '';
			$app_class = $this->mem['current_app_class'];
		}

		if ($cclass = 'wapi' || $cclass == 'WebApp') {
			$app_class = md5($cclass);
		}  elseif ($cclass == '') {
			$stop = '';
			$app_class = $this->mem['current_app_class'];
		} else {
			$stop = '';
			$app_class = $this->app_class;
		}
		if ($this->require_callback_ident) {
			return $this->saja->run($commands, $this->app_class, $process_file, $use_history,$this->callback_ident);
		} else {
			return $this->saja->run($commands, $this->app_class, $process_file, $use_history);
		}
	}
	private function runAsWapi($commands, $process_file=null, $use_history='false')
	{
		if ($this->require_callback_ident) {
			return $this->saja->run($commands, '', $process_file, $use_history,$this->callback_ident);
		} else {
			return $this->saja->run($commands, '', $process_file, $use_history);
		}
	}
	function secure_http()
	{
		$this->saja->secure_http();
	}
	function saja_js(){
		return $this->saja->saja_js();
	}
	function clear_secure_http()
	{
		$this->saja->clear_secure_http;
	}
	function send()
	{
		return $this->saja->send();
	}
	function runFunc($function, $php)
	{
		return $this->saja->runFunc($function, $php);
	}
	function hasActions(){
		return $this->saja->hasActions();
	}

################################################################################
#
#			SAJA RESPONSE FUNCTIONS
#
	//execute raw javascript code
	function js($js)
	{
		$this->saja->add_action($js);
	}
	//redirect the browser to a URL
	function redirect($url)
	{
		$this->saja->add_action("window.location = '$url'");
	}
	//return a javascript alert
	function alert($txt)
	{
		$this->saja->add_action("alert('".str_replace('\'', '\\\'', $txt)."')");
	}
	//submit a form on the page
	function submit($name)
	{
		$this->saja->add_action("document.forms['$name'].submit()");
	}
	//adds a new saja action to the queue
	function exec($action)
	{
		$this->saja->add_action($this->run($action));
	}
	//used for placing complex / long text into an element
	function text($content, $target)
	{
		$action = '';
        $targetProperty = '';
		list($target, $action) = $this->texplode(',', $target);
		list($targetId, $targetProperty) = $this->texplode(':', $target);
		if(!$action) $action = 'r';
		if(!$targetProperty) $targetProperty = 'innerHTML';
		$action = "saja.Put(".($this->saja->true_utf8 ? 'decodeURIComponent' : 'unescape')."('".rawurlencode($content)."'),'$targetId','$action','$targetProperty')";
		//$action = "saja.Put('".str_replace('\'', '\\\'', $content)."','$targetId','$action','$targetProperty')";
		$this->saja->add_action($action);
	}
	//hide an element
	function hide($element)
	{
		$this->saja->add_action("saja.Put('none','$element','r','style.display')");
	}
	//show an element
	function show($element)
	{
		$this->saja->add_action("saja.Put('','$element','r','style.display')");
	}
	//set style for an element
	function style($element, $styleString)
	{
		$this->saja->add_action("saja.SetStyle('$element', '$styleString')");
	}

	function texplode($seperator, $str)
	{
		$vals = array();
		foreach(explode($seperator, $str) as $val){
			if(is_numeric($val)){
				$vals[] = $val;
			} else if(strlen($val) > 0){
				$vals[] = trim($val);
			}
		}
		return $vals;
	}
	function quick_read($fname) {
	    $fdata = '';
	    if (is_file($fname)) {
	        $fdata = trim(file_get_contents($fname));
	    }
	    return $fdata;
	}

	function app_badge_note($note='') {
		$badge_id = $this->app_class . '_badge_tl';
		if ($note != '') {
			$_SESSION['APPS'][$this->app_class]['BADGE_NOTE'] = $note;
			$this->text($note,$badge_id);
			if (strlen($note) < 3){
				$this->text($note,$badge_id);
				$this->style($badge_id,'display:block;background-position:0px 24px;');
			} else {
				$this->style($badge_id,'display:block;background-position:0px 0px;');
			}
		} else {
			unset($_SESSION['APPS'][$this->app_class]['BADGE_NOTE']);
			$this->text('',$badge_id);
			$this->style($badge_id,'display:none;');
		}
	}
	private function app_badge_close($visible) {
		if ($this->app_class != '') {
			$badge_id = $this->app_class . '_badge_close';
			if ($visible) {
				$unload_code = $this->run("saja_app_unload_init()");
				$this->app_set('UNLOAD_CODE',$unload_code);
				$js_code = "document.getElementById(\"$badge_id\").onclick=\"$unload_code\"";
				$this->js($js_code);
				$this->style($badge_id,'display:block;');
			} else {
				unset($_SESSION['APPS'][$this->app_class]['UNLOAD_CODE']);
				$js_code = "document.getElementById(\"$badge_id\").onclick=\"\"";
				$this->js($js_code);
				$this->style($badge_id,'display:none;');
			}
		}
	}
}
?>